#include<iostream>
#include<string>
#include<unistd.h>
#include<pthread.h>

class Task
{
public:
    Task(int a,int b)
    :_a(a),_b(b)
    {

    }
    int Execute()
    {
        return _a + _b;
    }
    ~Task(){}
private:
    int _a;
    int _b;
};

class Result
{
public:
    Result(int result)
    :_result(result)
    {

    }
    ~Result(){}
    int GetResult()
    {
        return _result;
    }
private:
    int _result;
};

void* routine(void* args)
{
    Task *t = static_cast<Task*>(args);
    sleep(1);
    Result *res = new Result(t -> Execute());
    sleep(1);
    return res;
}

int main()
{
    pthread_t tid;
    Task *t = new Task(10,20);
    int n = pthread_create(&tid,nullptr,routine,t);
    if(n != 0)
    {
        std::cout << "pthread_create error: " << n << std::endl;
        exit(1); 
    }
    
    int cnt = 5;
    while(cnt--)
    {

        sleep(1); 
    }
    void* ret = nullptr;//用来存储线程的返回值
    pthread_join(tid,&ret);//通过进程的线程ID来等待进程,不等待进程可能会有内存泄露的风险.
    int h = ((Result *)ret) -> GetResult();//注意优先级
    std::cout << "h is: " << h << std::endl;
    delete t;
    delete (Result*)ret;
    return 0;
}
//该程序表示方法返回的可以是任意类型的